import { defineStore } from "pinia"
import { SysUserApi } from "../../api/user"

export const useUserStore = defineStore('useUserStore', {
    state: () => {
        return {
            userId: '',
            nickName: '',
            token: '',
            isAdmin: false,
            permissionCodeList: []
        }
    },
    getters: {
        getUserId(state) {
            return state.userId
        },
        getNickName(state) {
            return state.nickName
        },
        getToken(state) {
            return state.token
        },
        getIsAdmin(state) {
            return state.isAdmin
        },
        getPermissionCodeList(state) {
            return state.permissionCodeList
        }
    },
    actions: {
        setUserId(userId: string | number) {
            this.userId = userId + ''
        },
        setNickName(nickName: string) {
            this.nickName = nickName
        },
        setToken(token: string) {
            this.token = token
        },
        setIsAdmin(isAdmin: boolean) {
            this.isAdmin = isAdmin
        },
        setPermissionCodeList(permissionCodeList: []) {
            this.permissionCodeList = permissionCodeList
        },
        getUserInfo() {
            return new Promise((resolve, reject) => {
                SysUserApi.getUserInfo(this.userId).then(res => {
                    if (res && res.code === 200 && res.data) {
                        this.userId = res.data.userId
                        this.nickName = res.data.nickName
                        this.permissionCodeList = res.data.permissionCodeList
                    }
                    resolve(this.permissionCodeList)
                }).catch(err => {
                    reject(err)
                })
            })
        },
        clear() {
            this.userId = ''
            this.nickName = ''
            this.token = ''
        }
    },
    persist: {
        key: 'useUserStore',
        storage: sessionStorage,
        paths: ['userId', 'nickName', 'token', 'isAdmin']
    }
})